package cn.dakaqi.services.impl;

import cn.dakaqi.dao.PinganDayNumberDao;
import cn.dakaqi.entities.PinganDayNumber;
import cn.dakaqi.services.PinganNumberService;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author chunyang on 2016/4/19.
 */
@Component(value = "serialNumberService")
@Transactional
public class PinganNumberServiceImpl implements PinganNumberService
{
    public static final String OTHER = "9";

    @Autowired
    PinganDayNumberDao pinganDayNumberDao;

    @Override
    public String createNO(String type) throws ServiceRuntimeException
    {
        if(StringUtils.isBlank(type))
            type = OTHER;

        //查询指定类型当天的最大值
        String sn = "", numStr = "00001";
        String day = DateUtil.convertDefaultDateString(new Date());
        PinganDayNumber target = this.pinganDayNumberDao.findByTypeAndDay(type, day);
        if (null == target)
        {
            target = new PinganDayNumber();
            target.setDay(day);
            target.setNum(1);
            target.setType(type);
        }
        else
        {
            int num = target.getNum() + 1;
            target.setNum(num);
            if (num >= 10000)
                numStr = String.valueOf(num);
            else if (num >= 1000)
                numStr = "0" + String.valueOf(num);
            else if (num >= 100)
                numStr = "00" + String.valueOf(num);
            else if (num >= 10)
                numStr = "000" + String.valueOf(num);
            else
                numStr = "0000" + String.valueOf(num);
        }
        this.pinganDayNumberDao.save(target);
        sn = type + DateUtil.currentDateStringTrim() + DateUtil.currentTimeStringTrim() + numStr;
        return sn;
    }
}
